前兩天介紹了Restful API的常備知識,那今天就來實作看看到底怎麼設計吧!
這邊使用Python的FastAPI框架做示範,主題是查看,新增、刪除、修改庫存
└── stock
├── app.py
├── data
│ ├── config.py
│ ├── model.py
│ └── getstock.py
└── main.py
# -*- coding: utf-8 -*-
"""
服務主入口
"""
from typing import Optional
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from data.model import ProductBase
from data.getstock import (
get_Product, insert_Product, update_Product, delete_Product
)
router = APIRouter()
## 顯示商品
@router.get(f'/api/product')
async def AllProduct():
...
## 顯示商品資訊
@router.get("/api/product/{product_id}")
async def ProductInfo(product_id:str):
...
## 新增商品資訊
@router.post("/api/product", tags=['庫存'])
async def InsertProductInfo(product:ProductBase):
...
## 修改商品資訊
@router.put("/api/product/{product_id}", tags=['庫存'])
async def UpdateProductInfo(product_id:str, product:ProductBase):
...
## 刪除商品資訊
@router.delete("/api/product/{product_id}", tags=['庫存'])
async def DeleteProductInfo(product_id:str):
...
對應API文件
# -*- coding: utf-8 -*-
"""
資料格式設定檔
"""
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field
class ProductBase(BaseModel):
owner_id: str = Field(title='保管人')
owner_dept: str = Field(title='保管部門')
asset_id: str = Field(title='資產編號')
item_cate: str = Field(title='設備分類')
item_name: str = Field(title='財產品名')
item_factory: str = Field(title='廠商')
在API文件中就會呈現
getstock.py 跟db互動對資料進行CRUD
# -*- coding: utf-8 -*-
"""
商品資訊
"""
#%%
import pandas as pd
from pymongo import MongoClient
from datetime import datetime as dt
from .model import ProductBase
# 自定義商品流水編號
def get_productID():
...
# 顯示
def get_Product(product_id: None):
...
# 新增商品
def insert_Product(product: ProductBase):
...
# 更新商品資訊
def update_Product(product_id:str, product: ProductBase):
...
# 刪除商品資訊
def delete_Product(product_id:str):
...
# -*- coding: utf-8 -*-
"""
主程式檔
"""
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app import router
from data.config import config
API = config['API']['Url']
## swagger設定
app = FastAPI(
title=config['Swagger']['title'],
description=config['Swagger']['description'],
version=config['Swagger']['version'],
contact=config['Swagger']['contact'],
swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"},
docs_url=f"/{API}/docs", #指定路徑
openapi_url=f"/{API}/api/v1/openapi.json",
)
app.include_router(router)
如何執行檔案呢?進入資料夾中在cmd中輸入uvicorn main:app --reload --port 5100
port可以自行設定,網址需要對應docs_url指定路徑,因此我是要打開http://localhost:5100/stock/docs#/